package com.jshx.sz.gdjt.activity;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.jshx.sz.gdjt.R;
import com.jshx.sz.gdjt.bean.ProjectBean;
import com.jshx.sz.gdjt.constant.ApplicationGlobal;
import com.jshx.sz.gdjt.control.HeaderView;
import com.jshx.sz.gdjt.control.ToggleButtonView;
import com.jshx.sz.gdjt.control.ToggleButtonView.ToggleButtonStatu;
import com.jshx.sz.gdjt.util.ToastUtil;

/**
 * 项目详情界面
 * @author caxiang
 * @time 2013-08-20
 */
public class ProjectDetailActivity extends SuperActivity
{
	/**
	 * 标题栏组件
	 */
	private HeaderView header;
	
	/**
	 * 项目名称
	 */
	private TextView projectName;
	
	/**
	 * 项目要求
	 */
	private TextView projectOrder;
	
	/**
	 * 图片横向滑动组件
	 */
	private HorizontalScrollView scroll;
	
	/**
	 * 图片容器
	 */
	private LinearLayout notNormalImages;
	
	/**
	 * 备注组件
	 */
	private EditText projectRemark;
	
	/**
	 * 项目数据
	 */
	private ArrayList<ProjectBean> data;
	
	/**
	 * 图片数据容器
	 */
	private ArrayList<String> imageData;;
	
	/**
	 * 项目下标
	 */
	private int index = 0;
	
	/**
	 * 图片地址路径
	 */
	private String picName;
	
	/**
	 * 组件实例化工具
	 */
	private LayoutInflater layoutInflater;
	
	/**
	 * 开关按钮
	 */
	private ToggleButtonView toggle;
	
	//
	private final static String YES = "1";
	
	//
	private final static String NO = "0";
	
	/**
	 * 页面句柄
	 */
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) 
		{
			int what = msg.what;
			super.handleMessage(msg);
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.project_detail_activity);
		TAG = "ProjectDetailActivity";
		layoutInflater = LayoutInflater.from(this);
		data = getIntent().getParcelableArrayListExtra(ApplicationGlobal.LIST_DATA_FLAG);
		index = getIntent().getIntExtra("Index", 0);
		findView();
		initView();
	}
	
	/**
	 * 实例化页面组件
	 */
	private void findView() 
	{
		header = (HeaderView)findViewById(R.id.projectdetail_header);
		projectName = (TextView)findViewById(R.id.project_name);
		projectOrder = (TextView)findViewById(R.id.project_order);
		scroll = (HorizontalScrollView)findViewById(R.id.project_notnormal_pics);
		notNormalImages = (LinearLayout)findViewById(R.id.project_notnormal_picslayout);
		projectRemark = (EditText)findViewById(R.id.project_remark);
		toggle = (ToggleButtonView)findViewById(R.id.projectdetail_togglebtn);
	}

	/**
	 * 初始化页面数据和页面组件
	 */
	private void initView() 
	{
		header.setTitle("项目详情");
		header.setLeftButtonClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(ProjectDetailActivity.this, TaskCheckActivity.class);
				intent.putParcelableArrayListExtra(ApplicationGlobal.LIST_DATA_FLAG, data);
				data.get(index).setHasEdit("true");
				data.get(index).setRemark(projectRemark.getText().toString());
				setResult(RESULT_OK, intent);
				ProjectDetailActivity.this.finish();
			}
		}, R.drawable.titlebtn_select, "确定");
		header.setRightButtonClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				if(data != null && index < data.size() - 1)
				{
					data.get(index).setHasEdit("true");
					data.get(index).setRemark(projectRemark.getText().toString());
					projectRemark.setText("");
					notNormalImages.removeAllViews();
					imageData = null;
					toggle.setToggleButtonStatu(ToggleButtonStatu.STATU_LEFT);
					scroll.setVisibility(View.GONE);
					index++;
					projectName.setText(data.get(index).getProjectName());
					projectOrder.setText(data.get(index).getProjectContent());
					initImageData();
					refreshImages();
				}
				else
				{
					ToastUtil.showLongToast(ProjectDetailActivity.this, "已经是最后一项了...");
				}
			}
		}, R.drawable.titlebtn_select, "下一项");
		toggle.setLeftButtonClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				imageData = null;
				scroll.setVisibility(View.GONE);
				data.get(index).setResualt(YES);
				data.get(index).setResualtImagePaths(null);
			}
		});
		toggle.setRightButtonClickListener(new OnClickListener() 
		{
			@Override
			public void onClick(View v) {
				imageData = new ArrayList<String>();
				scroll.setVisibility(View.VISIBLE);
				data.get(index).setResualt(NO);
				imageData.add(new String());
				goCameraTakePhoto();
				refreshImages();
			}
		});
		projectName.setText(data.get(index).getProjectName());
		projectOrder.setText(data.get(index).getProjectContent());
		projectRemark.setText(data.get(index).getRemark());
		initImageData();
		refreshImages();
	}
	
	/**
	 * 初始话数据
	 */
	private void initImageData()
	{
		if(data.get(index).getResualt() != null && NO.equals(data.get(index).getResualt()))
		{
			toggle.setToggleButtonStatu(ToggleButtonStatu.STATU_RIGHT);
			String paths = data.get(index).getResualtImagePaths();
			if(paths != null && paths.contains(","))
			{
				String[] pathArray = paths.split(",");
				imageData = new ArrayList<String>();
				for (int i = 0; i < pathArray.length; i++) {
					imageData.add(0, pathArray[i]);
				}
			}
			if(imageData == null)
			{
				imageData = new ArrayList<String>();
			}
			imageData.add(new String());
			scroll.setVisibility(View.VISIBLE);
		}
	}
	
	/**
	 * 跳转拍照界面
	 */
	private void goCameraTakePhoto()
	{
		Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		picName = format.format(new Date()) + ".jpg";
		File f = new File(ApplicationGlobal.imageBaseFold + picName);
		if(!f.exists())
		{
			try {
				f.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Uri u = Uri.fromFile(f);
		intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
		startActivityForResult(intent, 0);//跳转至系统自带拍照界面
	}

	/**
	 * 刷新图片数据并更新视图
	 */
	private void refreshImages() {
		notNormalImages.removeAllViews();
		if(imageData != null && imageData.size() > 0)
		{
			for(int i = 0; i < imageData.size(); i++)
			{
				if(i < imageData.size() - 1)
				{
					View view = layoutInflater.inflate(R.layout.image_gallry_item, null);
					ImageView image = (ImageView)view.findViewById(R.id.gallery_image);
					ImageButton del = (ImageButton)view.findViewById(R.id.image_delete);
					Options opts = new Options();
					opts.inSampleSize = 2;
					image.setBackgroundDrawable(new BitmapDrawable(BitmapFactory
							.decodeFile(imageData.get(i), opts)));
					final int index = i;
					del.setOnClickListener(new OnClickListener() 
					{
						@Override
						public void onClick(View v) {
							imageData.remove(index);
							String S = "";
							for (int j = 0; j < imageData.size(); j++) 
							{
								if(imageData.get(j) != null && imageData.get(j).length() > 0)
								{
									if(j < imageData.size() - 1)
									{
										S += imageData.get(j) + ",";
									}
									else 
									{
										S += imageData.get(j);
									}
								}
							}
							data.get(ProjectDetailActivity.this.index).setResualtImagePaths(S);
							refreshImages();
						}
					});
					view.setOnClickListener(new OnClickListener() 
					{
						@Override
						public void onClick(View v) {
							Intent intent = new Intent(ProjectDetailActivity.this, PopActivity.class);
							intent.putExtra("isImage", true);
							Options opts = new Options();
							opts.inSampleSize = 2;
							ApplicationGlobal.globalDrawable = new BitmapDrawable(BitmapFactory
									.decodeFile(imageData.get(index), opts));
							startActivity(intent);
						}
					});
					notNormalImages.addView(view);
				}
				else
				{
					ImageView view = new ImageView(this);
					Options opts = new Options();
					opts.inSampleSize = 2;
					view.setBackgroundDrawable(getResources().getDrawable(R.drawable.addimage_select));
					LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
					lp.gravity = Gravity.CENTER_VERTICAL;
					view.setLayoutParams(lp);
					view.setOnClickListener(new OnClickListener() 
					{
						@Override
						public void onClick(View v) {
							goCameraTakePhoto();
						}
					});
					notNormalImages.addView(view);
				}
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) 
	{
		if(requestCode == 0 && resultCode == RESULT_OK)
		{
			String path = ApplicationGlobal.imageBaseFold + picName;
			imageData.add(0, path);
			if(data.get(index).getResualtImagePaths() == null || data.get(index).getResualtImagePaths().length() < 1)
			{
				data.get(index).setResualtImagePaths(path + ",");
			}
			else
			{
				data.get(index).setResualtImagePaths(data.get(index).getResualtImagePaths() + path + ",");
			}
			refreshImages();
		}
		super.onActivityResult(requestCode, resultCode, intent);
	}
}
